//
//  SFSegmentViewController.m
//  Yanwei
//
//  Created by 刘文 on 16/9/28.
//  Copyright © 2015年 ouer. All rights reserved.
//

#import "SFSegmentViewController.h"

#define DefaultSegmentHeight 44

@interface SFSegmentViewController () <UIScrollViewDelegate, SFSegmentControlDelegate>

@property(nonatomic, strong) SFSegmentControl   *segmentControl;
@property(nonatomic)         CGFloat            beginOffsetX;
@property(nonatomic, strong) UIScrollView       *scrollView;
@property (nonatomic, copy) UIView *lineView;

@end

@implementation SFSegmentViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.segmentControl];
    [self.view addSubview:self.scrollView];
    
    self.lineView.hidden = NO;
    
    //  监听contentScrollView
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
}

#pragma mark - Private Method

- (void)selectNext {
    if (self.segmentControl.selectIndex + 1 < self.viewControllers.count) {
        
        self.segmentControl.selectIndex = self.segmentControl.selectIndex + 1;
    }
}

- (void)selectPrevious {
    if (self.segmentControl.selectIndex > 0) {
        
        self.segmentControl.selectIndex = self.segmentControl.selectIndex - 1;
    }
}

#pragma mark - lazy initializer
- (SFSegmentControl *)segmentControl {
    if (!_segmentControl)
    {
//        CGFloat y = 0;//!self.navigationController?20:64;
        CGFloat y;
        if (!self.navigationController) {
            y = 20;
        } else {
            if (self.navigationController.isNavigationBarHidden) {
                y = 20;
            } else {
                if (self.hasDistance) {
                    y = 64;
                } else {
                    y = 0;
                }
            }
        }
        if (self.segmentControlIsNoSpacing) {
            y = 0;
        } else {
            if (APP.iPhoneType == iPhoneX) {
                y += 20;
            }
        }
        _segmentControl = [[SFSegmentControl alloc] initWithFrame:CGRectMake(0, y, [UIScreen mainScreen].bounds.size.width, DefaultSegmentHeight)];
        if (self.controllerShowType == ControllerShowTypeShowNavigation) {
            _segmentControl.top = APP.iPhoneType == iPhoneX ? 42 : 20;
            _segmentControl.width = ScreenWidth - 90 -100 *CalculateSuitableSize;
            _segmentControl.centerX = self.view.centerX;
        }
        _segmentControl.delegate = self;
    }
    return _segmentControl;
}

- (UIScrollView *)scrollView
{
    //  scrollView
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentControl.frame), [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(_segmentControl.frame) - 48)];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.decelerationRate = 0.5;
        if (self != nil && _scrollView != nil) {
            _scrollView.delegate = self;
        }
        _scrollView.alwaysBounceVertical = NO;
        _scrollView.scrollsToTop = NO;
        _scrollView.backgroundColor = [UIColor whiteColor];
    }
    return _scrollView;
}

- (UIButton *)leftBarItemButton {
    if (!_leftBarItemButton) {
        _leftBarItemButton = [UIButton buttonWithType:UIButtonTypeSystem];
//        _leftBarItemButton.frame = CGRectMake(10, 6, 30, 30);
        _leftBarItemButton.left = 5;
        _leftBarItemButton.top = APP.iPhoneType == iPhoneX ? 42 : 20;//self.segmentControl.centerY;
        _leftBarItemButton.height = self.segmentControl.height;
        _leftBarItemButton.width = 40;
        _leftBarItemButton.hidden = YES;
        [_leftBarItemButton setTitle:ARROW_LEFT forState:UIControlStateNormal];
        [_leftBarItemButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _leftBarItemButton.titleLabel.font = ICONFONT(defaultFontSize +3);
        [self.view addSubview:_leftBarItemButton];
//        [_leftBarItemButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(self.view).with.offset(10);
//            make.top.equalTo(self.segmentControl);
//            make.right.equalTo(self.segmentControl.mas_left);
//            make.bottom.equalTo(self.segmentControl);
//        }];
    }
    return _leftBarItemButton;
}

- (UIButton *)rightBarItemButton {
    if (!_rightBarItemButton) {
        _rightBarItemButton = [UIButton buttonWithType:UIButtonTypeSystem];
        CGFloat top = APP.iPhoneType == iPhoneX ? 42 : 20;
        _rightBarItemButton.frame = CGRectMake(ScreenWidth - 40 - 10, top, 40, 44);
        [_rightBarItemButton setTitle:N_SHARE forState:UIControlStateNormal];
        [_rightBarItemButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _rightBarItemButton.titleLabel.font = ICONFONT(defaultFontSize +3);
        _rightBarItemButton.hidden = YES;
        [self.view addSubview:_rightBarItemButton];
    }
    return _rightBarItemButton;
}
- (UIButton *)otherRightBarItemButton {
    if (!_otherRightBarItemButton) {
        _otherRightBarItemButton = [UIButton buttonWithType:UIButtonTypeSystem];
        CGFloat top = APP.iPhoneType == iPhoneX ? 42 : 20;
        _otherRightBarItemButton.frame = CGRectMake(ScreenWidth - 40 - 10, top, 40, 44);
        [_otherRightBarItemButton setTitleColor:NewStoreLevelSecondSubtitleColor forState:UIControlStateNormal];
        _otherRightBarItemButton.titleLabel.font = APPFONT(defaultFontSize);
        _otherRightBarItemButton.hidden = YES;
        [self.view addSubview:_otherRightBarItemButton];
    }
    return _otherRightBarItemButton;
}
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.segmentControl.frame) - 0.5, ScreenWidth, 0.5)];
        _lineView.backgroundColor = NewStoreDividingLineColor;
        [self.view addSubview:_lineView];
    }
    return _lineView;
}


#pragma mark - Setters
- (void)setIsHiddenLineView:(BOOL)isHiddenLineView {
    _isHiddenLineView = isHiddenLineView;
    
    self.lineView.hidden = _isHiddenLineView;
}
- (void)setHasDistance:(BOOL)hasDistance {
    _hasDistance = hasDistance;
}

- (void)setControllerShowType:(ControllerShowType)controllerShowType {
    if (_controllerShowType == controllerShowType) {
        return;
    }
    self.scrollView.pagingEnabled = YES;
    self.scrollView.decelerationRate = 1;
    _controllerShowType = controllerShowType;
    switch (controllerShowType) {
        case ControllerShowTypeFullScreen: {
            self.scrollView.top = 0;
            self.scrollView.height = ScreenHeight;
            break;
        }
        case ControllerShowTypeShowNavigation: {
//            self.segmentControl.top = 20;
//            self.segmentControl.width = ScreenWidth - 90;
//            self.segmentControl.left = 44;
            self.scrollView.top = self.segmentControl.bottom;
            self.scrollView.height = ScreenHeight - self.segmentControl.bottom;
//            self.leftBarItemButton.top = 20;
            self.leftBarItemButton.hidden = NO;
//            self.rightBarItemButton.hidden = NO;
            break;
        }
            
        default:
            break;
    }
    
}
- (void)setSegmentControlIsNoSpacing:(BOOL)segmentControlIsNoSpacing {
    _segmentControlIsNoSpacing = segmentControlIsNoSpacing;
}

- (void)setRoll:(BOOL)roll {
    _roll = roll;
    self.scrollView.scrollEnabled = roll;
}

- (void)setSegmentType:(SFSegmentType)segmentType
{
    _segmentType = segmentType;
    self.segmentControl.segmentType = segmentType;
}

- (void)setSegmentBackgroundColor:(UIColor *)segmentBackgroundColor
{
    _segmentBackgroundColor = segmentBackgroundColor;
    self.segmentControl.backgroundColor = segmentBackgroundColor;
}

- (void)setSegmentBackgroundImage:(UIImage *)segmentBackgroundImage
{
    _segmentBackgroundImage = segmentBackgroundImage;
    self.segmentControl.backgroundImage = segmentBackgroundImage;
}

- (void)setSegmentHighlightColor:(UIColor *)segmentHighlightColor
{
    _segmentHighlightColor = segmentHighlightColor;
    self.segmentControl.highlightColor = segmentHighlightColor;
}

- (void)setSegmentLineWidth:(CGFloat)segmentLineWidth
{
    _segmentLineWidth = segmentLineWidth;
    self.segmentControl.lineWidth = segmentLineWidth;
}

- (void)setSegmentBorderWidth:(CGFloat)segmentBorderWidth
{
    _segmentBorderWidth = segmentBorderWidth;
    self.segmentControl.borderWidth = segmentBorderWidth;
}

- (void)setSegmentBorderColor:(UIColor *)segmentBorderColor
{
    _segmentBorderColor = segmentBorderColor;
    self.segmentControl.borderColor = segmentBorderColor;
}

- (void)setSegmentTitleColor:(UIColor *)segmentTitleColor
{
    _segmentTitleColor = segmentTitleColor;
    self.segmentControl.titleColor = segmentTitleColor;
}

- (void)setSegmentHighlightTitleFont:(UIFont *)segmentHighlightTitleFont {
    _segmentHighlightTitleFont = segmentHighlightTitleFont;
    
    self.segmentControl.highlightTitleFont = segmentHighlightTitleFont;
}

- (void)setSegmentTitleFont:(UIFont *)segmentTitleFont
{
    _segmentTitleFont = segmentTitleFont;
    self.segmentControl.titleFont = segmentTitleFont;
}

- (void)setCanScrollow:(BOOL)canScrollow {
    _canScrollow = canScrollow;
    
    self.scrollView.scrollEnabled = _canScrollow;
}

- (void)setViewControllers:(NSArray *)viewControllers
{
    _viewControllers = viewControllers;
    [self.childViewControllers enumerateObjectsUsingBlock:^(UIViewController *child, NSUInteger idx, BOOL * _Nonnull stop) {
        [child removeFromParentViewController];
    }];
    
    //  initialize
    NSMutableArray *arrayTitle = [[NSMutableArray alloc] init];
    for (UIViewController *c in self.viewControllers) {
        [arrayTitle addObject:c.title];
    }
    self.segmentControl.titles = arrayTitle;
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.scrollView.frame) * self.viewControllers.count, CGRectGetHeight(self.scrollView.frame));
    [self.segmentControl load];
}

#pragma mark - SFSegmentControlDelegate
- (void)SFSegmentSelectAtIndex:(NSInteger)index animation:(BOOL)animation
{
    [self.viewControllers enumerateObjectsUsingBlock:^(UIViewController *  _Nonnull controller, NSUInteger idx, BOOL * _Nonnull stop)
     {
         [controller removeFromParentViewController];
     }];
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    //  add controller
    UIViewController *controller = self.viewControllers[index];
    
    //  add view
    UIView *view = controller.view;
    [view removeFromSuperview];
    view.frame = CGRectMake(index * CGRectGetWidth(self.scrollView.frame), 0, CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
    
    [controller willMoveToParentViewController:self];
    [self addChildViewController:controller];
    [controller didMoveToParentViewController:self];
    [self.scrollView addSubview:view];
    
    //  add next view
    if (index + 1 < self.viewControllers.count) {
        UIViewController *nextController = self.viewControllers[index + 1];
        UIView *nextView = nextController.view;
        [nextView removeFromSuperview];
        nextView.frame = CGRectMake((index + 1) * CGRectGetWidth(self.scrollView.frame), 0, CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
        [self.scrollView addSubview:nextView];
    }
    
    //  add previous view
    if (index - 1 >= 0) {
        UIViewController *previousController = self.viewControllers[index - 1];
        UIView *previousView = previousController.view;
        [previousView removeFromSuperview];
        [self.scrollView addSubview:previousView];
        previousView.frame = CGRectMake((index - 1) * CGRectGetWidth(self.scrollView.frame), 0, CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
    }
    
    [self.scrollView scrollRectToVisible:view.frame animated:animation];
    
    if (self.block) {
        self.block(index);
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (!scrollView.isDecelerating) {
        self.beginOffsetX = CGRectGetWidth(scrollView.frame) * self.segmentControl.selectIndex;
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    scrollView.userInteractionEnabled = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat targetX = targetContentOffset->x;
    NSInteger selectIndex = targetX/CGRectGetWidth(self.scrollView.frame);
    self.segmentControl.selectIndex = selectIndex;
    if (self.block) {
        self.block(selectIndex);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"] && !self.scrollView.isDecelerating && self.scrollView.isDragging) {
        
        CGPoint contentOffset = [[change valueForKey:NSKeyValueChangeNewKey] CGPointValue];
        CGFloat rate = (contentOffset.x - self.beginOffsetX)/CGRectGetWidth(self.scrollView.        
frame);
        [self.segmentControl scrollToRate:rate];
    }
}

- (void)segmentControlSelectedIndex:(SegmentControlSelectedIndex)block {
    self.block = block;
}

@end
